import React from 'react';
import base from './base';
import * as API_REQ from '../apis/form';
import { Modal, Bubble ,Checkbox, Toast} from 'weaver-mobile';
import {Browser, BrowserHrm} from 'weaver-mobile-page';
import { _, WfForm_Public,GlobalUtil } from './pcPublic';
import * as Util from './formUtil';
import * as Common from './common';
import { doSubmitForm,doSubmitReady,doSubmitPost,generateFormData } from './submit';
import * as VariableKeys from '../constants/variableKey';
import * as SignUtil  from './SignUtil';
import * as EmSDK from "./emSDK";
import * as formBtnUtil from './formBtnUtil'
import { toJS } from 'mobx'
import * as API_SUPERVISE from '../apis/supervise'
const getLabel = Common.getLabel;
const getAntd = () =>{};
const verifyCustomRegisterEvent = GlobalUtil.verifyCustomRegisterEvent;

//提交需反馈
export const doSubmitBack = () => {
	const { wfGlobalStore,wfOperateStore } = base;
	const { commonParam } = wfGlobalStore;
	const { rightMenu,submitParam = {}} = wfOperateStore;
	const { iscreate,selectNextFlowPattern} = commonParam;
	const { isFree} = rightMenu;
	//如果是自由流程,判断是否为创建否则直接提交
	//移动端暂时不支持流转设置
	if(isFree == "1" && iscreate == "1" && (selectNextFlowPattern == 0 && submitParam.operatorids == "")){
		doFreeWorkflow();
	}else{
		wfOperateStore.setSubmitToNodeId();
		doSubmitForm({actiontype:"requestOperation", src:"submit", needwfback:"1"});
	}
	
}

//提交不需反馈
export const doSubmitNoBack = () => {
	const { wfGlobalStore,wfOperateStore } = base;
	const { commonParam } = wfGlobalStore;
	const { rightMenu,submitParam = {}} = wfOperateStore;
	const { iscreate,selectNextFlowPattern} = commonParam;
    const { isFree} = rightMenu;
	if(isFree == "1" && iscreate == "1" && (selectNextFlowPattern == 0 && submitParam.operatorids == "")){
		doFreeWorkflow();
	}else{
		wfOperateStore.setSubmitToNodeId();
		doSubmitForm({actiontype:"requestOperation", src:"submit", needwfback:"0"});
	}
}

//流程保存
export const doSave_nNew = () => {
	doSubmitForm({actiontype:"requestOperation", src:"save"});
}

//提交后确认按钮
export const doSubmit_Pre = (src = 'submit') => {
	doSubmitForm({actiontype:"requestOperation", src});
}
//流程关注
export const doAttention = () => {
	const { wfGlobalStore } = base;
	const { requestid } = wfGlobalStore.commonParam;
	window.historyRoute.push({
		pathname: "/req/follow",
		state:{requestids:requestid,mode:'single',flag:'detail'},
        callback: (reVal) =>{
           
        }
    });
}
 
/**流程督办  by  lijia 2018-12-28***************/
export const doSupervise = () => {
	const {  wfSignInputStore ,wfOperateStore} = base.allStores;
	const { batchControlVariableMap, showSignInput,hiddenSignInput,forwardClear,ckStore} = wfSignInputStore;
	const isShowSignInput = SignUtil.getVariableMapVal(VariableKeys.SHOW_SIGN_AREA, false);
	if (!isShowSignInput) {//如果签字意见框没有打开
		wfSignInputStore.isurger = true;
		// let updateVariable = {};
		// updateVariable[VariableKeys.SHOW_SIGN_AREA] = true;
		// updateVariable[VariableKeys.SHOW_SIGN_BTN] = false;
		// batchControlVariableMap(updateVariable);
		// formBtnUtil.getEmBottomBtns();
		showSignInput({}, 'duban');
	} else{
		
		const { wfGlobalStore } = base;
		const { requestid,f_weaver_belongto_userid } = wfGlobalStore.commonParam;
		const {markInfo = {},isRichText} = wfOperateStore;
		let remark = SignUtil.getVariableMapVal(VariableKeys.SIGN_CONTENT);
		if(isRichText && ckStore.isInited) {
			remark = ckStore.getData();
		}
		let _remark = SignUtil.remarkFilter(remark);    

		//处理引用
		const remarkQuote = SignUtil.getRemarkQuoteData(_remark);
		let tempRequestid = requestid.toString() + '_' + f_weaver_belongto_userid.toString();
		const params = { requestids: tempRequestid, ...remarkQuote, ...SignUtil.getSignInfoDatas() };
		wfGlobalStore.setLoading(true);
		API_SUPERVISE.doSupervise(params).then(data => {
			wfGlobalStore.setLoading(false);
			if (data.result) {
				Bubble.success(getLabel(387108, '督办成功'));
				
				//清空签字意见
				let updateParams = {};
				updateParams[VariableKeys.SIGN_CONTENT] = '';
				hiddenSignInput(updateParams);

				setTimeout(() => {
					//刷新签字意见区域
					const reloadLogListParams = {pgnumber: 1, atmet: '', maxrequestlogid: 0};
					const {updateLogParams,activeKey,setState} = base.allStores.wfSignListStore;
					if(activeKey != '1')  setState({activeKey:'1'});
					updateLogParams(reloadLogListParams, true);
				}, 200);
			} else {
				Bubble.error(getLabel(387109, '督办失败'));
			}
		});
	}
}


//流程干预
export const doIntervenor = () =>{
	const { wfGlobalStore, allStores } = base;
	const { invertionInfo = {} } = wfGlobalStore;
	const { items = [] } = invertionInfo;
	const { location = {} } = window.historyRoute
	const { pathname = "" } = location;
	if (pathname != "/req/intervenor") {
		allStores.wfIntervenor.form.initForm(items, '/req/intervenor');
		items.length > 0 && items.map(v => {
			if (v.domkey[0] == "submitNodeId") {
				v.options.length > 0 && v.options.map(t => {
					if (t.selected) {
						allStores.wfIntervenor.setNodeName(t.showname);
					}
				})
			}
		})
		window.historyRoute.push("/req/intervenor");
	}
}

//流程暂停
export const doStop = () => {
	doFunctionLink("stop");
}

//流程撤销
export const doCancel = () => {
	doFunctionLink("cancel");

}

//流程启用
export const doRestart = () => {
	doFunctionLink("restart");
}

//流程删除
export const doDelete = () => {
	Common.showConfirm({
		title: getLabel(16667, ' 你确定删除该工作流吗？ '),
		okEvent: () => {
			verifyCustomRegisterEvent(WfForm_Public.OPER_DELETE, () =>{
				doSubmitPost({ src: "delete", actiontype: "requestOperation" });
			});
		},
		cancelEvent:()=>{
			const { controlVariableMap } = base.allStores.wfSignInputStore;
			controlVariableMap(VariableKeys.CURR_OPERATE_TYPE,{});
		}
	});
}

//流程删除(监控中的)
export const doMonitorDel = () => {
	const { wfGlobalStore } = base;
	const { requestid } = wfGlobalStore.commonParam;
	let params = {
		multiRequestIds: requestid
	}
	Common.showConfirm({
		title: getLabel(503689, ' 您确定要删除当前流程吗？ '),
		okEvent: () => {
			wfGlobalStore.setLoading(true);
			API_REQ.doMonitorDel(params).then(results => {
				const { success } = results;
				const { actionfail } = results;
				wfGlobalStore.setLoading(false);
				if (success) {
					Bubble.success(getLabel(83472, "删除成功"), 2)
					setTimeout(() => {
						Util.returnSourcePage();
					}, 2000);
				} else if(actionfail){
					let errmsg2 = getLabel(522595,'流程删除附加操作')+getLabel(83071,'执行失败')+'，'+getLabel(20462,'删除失败！');
					//let msg = (<div><p>{errmsg2}</p></div>);
					Bubble.error(errmsg2, 2);
				}else{
					Bubble.error(getLabel(83473,"删除失败"), 2)
				}
			})
		}
	});
	
}

//强制收回
export const doRetract = () => {
	verifyCustomRegisterEvent(WfForm_Public.OPER_TAKEBACK, () => {
		const { commonParam } = base.wfGlobalStore;
		const { requestid, workflowid, f_weaver_belongto_userid, f_weaver_belongto_usertype } = commonParam;
		API_REQ.functionLink({
			flag: "rb",
			requestid: requestid,
			workflowid: workflowid,
			f_weaver_belongto_userid: f_weaver_belongto_userid,
			f_weaver_belongto_usertype: f_weaver_belongto_usertype
		}).then(data => {
			Util.reloadRequestPage({ requestid , sessionkey : data.sessionkey});
		});
	});
}

//强制收回(监控中的)*
export const doMonitorRB = () => {
	const { wfGlobalStore } = base;
	const { requestid } = wfGlobalStore.commonParam;
	let params = {
		multiRequestIds: requestid,
	}
	wfGlobalStore.setLoading(true);
	API_REQ.doMonitorRB(params).then(results => {
		wfGlobalStore.setLoading(false);
		if (results.success == 1) {
			Bubble.success(getLabel(130233, "收回成功")) 
			setTimeout(() => {
				Util.returnSourcePage();
			}, 2000);
		} else {
			Bubble.error(getLabel(383604, "收回失败")) 
		}
		if(results.specialAddinoperateMsg) {
			Bubble.error(results.specialAddinoperateMsg);
		}
	})
}

//强制归档（监控中的）
export const doDrawBack = () => {
	const { wfGlobalStore, wfOperateStore } = base;
	const { commonParam, baseParam } = wfGlobalStore;
	const { requestid, needconfirm } = commonParam;
	const drawBackFun = () => {
		if (SignUtil.verifyRemark({needCheck:true,src:'arichive'})) { 
			const { submitParam } = wfOperateStore;
			const formDatas = generateFormData();   //表单字段参数
			const signInfo = SignUtil.getSignInfoDatas() || {};
			const allParams = { ...submitParam, ...formDatas,...signInfo, flag: "ov", fromflow: 1 , ...SignUtil.getSignInfoDatas()};
			wfGlobalStore.setLoading(true);
			API_REQ.functionLink(allParams).then(data => {
				wfGlobalStore.setLoading(false);
				Bubble.success(getLabel(503690, "归档成功"));
				setTimeout(() => {
					Util.returnSourcePage({source : 'forceOver'});
				}, 2000);
			});
		}
	}
	if (needconfirm == '1') {
		Common.showConfirm({
			title: getLabel(24703, '您确定将该流程强制归档吗？'),
			okEvent: () => {
				drawBackFun();
			}
		});
	} else {
		drawBackFun();
	}
}

// //强制归档
// export const doDrawBack = () => {
// 	const { wfGlobalStore, wfOperateStore } = base;
// 	const { commonParam, baseParam } = wfGlobalStore;
// 	const { submitParam } = wfOperateStore;
// 	const { requestid, needconfirm } = commonParam;
// 	const drawBackFun = () => {
// 		if (SignUtil.verifyRemark(true)) {
// 			const formDatas = generateFormData();   //表单字段参数
// 			const allParams = { ...submitParam, ...formDatas, flag: "ov", fromflow: 1 };
// 			wfGlobalStore.setLoading(true);
// 			API_REQ.functionLink(allParams).then(data => {
// 				wfGlobalStore.setLoading(false);
// 				Util.returnSourcePage();
// 			});
// 		}
// 	}
// 	if (needconfirm == '1') {
// 		Common.showConfirm({
// 			title: getLabel(24703, '您确定将该流程强制归档吗？'),
// 			okEvent: () => {
// 				drawBackFun();
// 			}
// 		});
// 	} else {
// 		drawBackFun();
// 	}
// }

/*** by  lijia 2018-12-28*************** */

//批注需反馈
export const doRemark_nBack = () => {
	doSubmitForm({ actiontype: "remarkOperation", src: "save", needwfback: "1" });
}

//批注不需反馈
export const doRemark_nNoBack = () => {
	doSubmitForm({ actiontype: "remarkOperation", src: "save", needwfback: "0" });
}

const doFunctionLink = (flag) => {
	const { commonParam } = base.wfGlobalStore;
	const { requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype } = commonParam;
	let content = "";
	let success_info = "";
	let failure_info = "";
	switch(flag){
		case 'stop':
			content = getLabel(26156, '您确定要暂停当前流程吗？');
			success_info = getLabel(503692,"暂停成功");
			failure_info = getLabel(503693,"暂停失败");
			break;
		case 'cancel':
			content = getLabel(26157, '您确定要撤销当前流程吗 ？');
			success_info = getLabel(504347,"撤销成功");
			failure_info = getLabel(503695,"撤销失败");
			break;
		case 'restart':
			content = getLabel(26158, '您确定要启用当前流程吗？');
			success_info = getLabel(388863,"启用成功");
			failure_info = getLabel(388864,"启用失败");
			break;
	}
	Common.showConfirm({
		title: content,
		okEvent: () => {
			base.wfGlobalStore.setLoading(true);
			API_REQ.functionLink({requestid,flag,f_weaver_belongto_userid,f_weaver_belongto_usertype}).then(data => {
				base.wfGlobalStore.setLoading(false);
				Bubble.success(success_info)
				setTimeout(() => {
					Util.returnSourcePage();
				}, 2000);
			});
		},
		cancelEvent:()=>{
			const { controlVariableMap } = base.allStores.wfSignInputStore;
			controlVariableMap(VariableKeys.CURR_OPERATE_TYPE,{});
		}
	});
}


//新建任务列表
export const openTaskList = () => {

}

//新建任务
export const doCreateTask = () => {

}

//退回确认节点
export const doReject_New = () => {
	if(SignUtil.verifyRemark({needCheck:true, src:"reject",needPrompt:true,isOnlyVerify:true})){
		const { wfGlobalStore,rejectStore } = base;
		const { commonParam } = wfGlobalStore;
		const { requestid,workflowid,nodeid,f_weaver_belongto_userid,f_weaver_belongto_usertype } = commonParam;
		API_REQ.judgeRejectWay({requestid,workflowid,nodeid,f_weaver_belongto_userid,f_weaver_belongto_usertype}).then(data =>{
			const { rejecttype,params } = data;
			if(rejecttype === 0){
				sureReject();
			}else if(rejecttype === 1){
				const { RejectNodes,RejectToNodeid } = params;
				sureReject(RejectNodes, RejectToNodeid);
			}else if(rejecttype === 2){	//弹窗选择退回节点及提醒节点
				window.historyRoute.push({
					pathname: "/req/reject",
					chooseInfo: data.chooseInfo,
					callback: (result) =>{
						if(!_.isEmpty(result)){
							const { rejectNodeKey="",remindNodeid="",isSubmitDirect="" } = result;
							const rejectNodeArr = rejectNodeKey.split("_");
							sureReject(remindNodeid, rejectNodeArr[0], rejectNodeArr[1], isSubmitDirect);
						}
					}
				});
			}
		});
	}
}

//流程退回
export const sureReject = (RejectNodes,RejectToNodeid,RejectToType,isSubmitDirect) => {
	const { commonParam } = base.wfGlobalStore;
	const { needconfirm } = commonParam;
	let params = {src:"reject", actiontype:"requestOperation", RejectNodes, RejectToNodeid, RejectToType, isSubmitDirect,'isFirstSubmit':'0'};
	if(needconfirm == "1")
		_.merge(params, {src:"save", isaffirmance:"1", isaffirmanceSrc:"reject"});
	doSubmitReady(params);
}


//表单修改日志
export const doViewModifyLog = () => {

}


//提交
export const doSubmitDirect = (subfun) => {
	const { wfGlobalStore,wfOperateStore, allStores} = base;
	const { submitParam,rightMenu,setSubmitToNodeId } = wfOperateStore;
	const {secondAuthStore} = allStores;
	const { ifchangstatus } = submitParam;
	const { hasback, hasnoback,lastnodeid } = rightMenu;
    setSubmitToNodeId(true);
	if(ifchangstatus != "" && (hasback == "1" || (hasback == "" && hasnoback == ""))) {
		if(subfun == "Affirmance") {
			doAffirmanceBack();
		} else {
			secondAuthStore.setIsSubmitDirect(1);
			doSubmitBack();
		}
	} else {
		if(subfun == "Affirmance") {
			doAffirmanceNoBack();
		} else {
			secondAuthStore.setIsSubmitDirect(1);
			doSubmitNoBack();
		}
	}
}

//转发、意见征询、转办等
const controlForward = (params = {}) =>{
	const {forwardflag = '1',needwfback = '',operator, isMulitTak} = params;
	let opertype = WfForm_Public.OPER_FORWARD;
	if(forwardflag == "2")
		opertype = WfForm_Public.OPER_ASKOPINION;
	else if(forwardflag == "3")
		opertype = WfForm_Public.OPER_TURNHANDLE;
	else if(forwardflag == "4")
		opertype = WfForm_Public.OPER_TURNREAD;
    
  //意见征询、转发、 传阅按钮点击，清空signStore中的缓存变量值
	if(forwardflag == '2' || forwardflag == '4' || forwardflag == '1') {
    const {wfSignInputStore} = base.allStores;
    wfSignInputStore.tsValue = {};
    wfSignInputStore.selectPassParams = {};
  }
	verifyCustomRegisterEvent(opertype, () =>{
		const {wfOperateStore,wfSignInputStore} = base.allStores;
        const {commonParam={}} = base.wfGlobalStore;
        const {workflowid='',nodeid='',beagenter='',f_weaver_belongto_userid='',f_weaver_belongto_usertype=''} = commonParam;
		//显示转发区域
		const {setShowSignArea,showSignArea = false, submitParam = {}} = wfOperateStore;
		const { agentType, agentorByAgentId } = submitParam;
		let updateVariable = {};
		updateVariable[VariableKeys.SHOW_SIGN_AREA] = true;
		updateVariable[VariableKeys.FORWARD_VISIABLE] = true;
		//转发控制参数
		const {batchControlVariableMap,setForwardParams,setForwardOperators,forwardOperatorDatas = [],forwardHrmStore} = wfSignInputStore;
		if(operator) {
			setForwardOperators(operator.id,[operator]);
		} else {
			setForwardOperators('',[]);
		}
		setForwardParams({forwardflag:forwardflag,needwfback:needwfback,workflowid:workflowid,nodeid:nodeid,bdf_wfid:workflowid,beagenter:beagenter,f_weaver_belongto_userid:f_weaver_belongto_userid,f_weaver_belongto_usertype:f_weaver_belongto_usertype,agentType:agentType,agentorByAgentId:agentorByAgentId,isMulitTak});
		
		wfSignInputStore.getFwLimitBrowserSet(()=>{
			batchControlVariableMap(updateVariable);
			if(forwardOperatorDatas.length === 0 && !operator) {
				window.historyRoute.push(forwardHrmStore.path);
			}else{
				EmSDK.controlBottomBtn('/req');
			}
		});
		
		SignUtil.asyncSignInfo(true);
		SignUtil.setMetaViewport(false);
		if(forwardflag == '1'){
			const { commonParam } = base.wfGlobalStore;
		const { requestid  } = commonParam;
		wfSignInputStore.clearformButtomFlag();
		wfSignInputStore.clearInquiryVariate();
		wfSignInputStore.getShowReplyNotice({requestid : requestid,f_weaver_belongto_userid:f_weaver_belongto_userid,f_weaver_belongto_usertype:f_weaver_belongto_usertype});
    }
    if(forwardflag == '4') {
      const { commonParam } = base.wfGlobalStore;
			const { requestid  } = commonParam;
      wfSignInputStore.clearformButtomFlag();
      wfSignInputStore.clearInquiryVariate();
      wfSignInputStore.getSelectInfo({requestid:requestid, forwardflag: '4',f_weaver_belongto_userid:f_weaver_belongto_userid,f_weaver_belongto_usertype:f_weaver_belongto_usertype});
    }
	});
}

//转发
export const doReviewE9 = (operator) => {
    verifyCustomRegisterEvent(WfForm_Public.OPER_FORWARD, () =>{
        controlForward({showForward:true, forwardflag:"1",operator});
    });
}

//转发收回
export const doReviewE9Back = () => {
    const { commonParam } = base.wfGlobalStore;
    const { requestid  } = commonParam;
    window.historyRoute.push({
        pathname: "/req/forwardback",
        callback: (reVal) =>{
            if(reVal.success){
                Util.reloadRequestPage({requestid});
            }
        }
    });
}

//转办需反馈
export const doReviewback3 = () => {
	controlForward({showForward:true, forwardflag:"3", needwfback:"1"});
}

//转办
export const doReview3 = (resourceid) =>{
	controlForward({showForward:true, forwardflag:"3"});
}

//意见征询
export const doReview2 = (resourceid) =>{
	controlForward({showForward:true, forwardflag:"2"});
}

//多级意见征询
export const doMultiTak = (resourceid) =>{
    controlForward({showForward:true, forwardflag:"2", isMulitTak:true});
}

//征询转办需反馈
export const doTakForward_Back = (resourceid) =>{
	controlForward({showForward:true, forwardflag:"5", needwfback : '1'});
}

//征询转办不需反馈
export const doTakForward_noBack = (resourceid) =>{
	controlForward({showForward:true, forwardflag:"5", needwfback : '0'});
}

//转办不需反馈
export const doReviewnoback3 = (resourceid) =>{
	controlForward({showForward:true, forwardflag:"3", needwfback:"0"});
}

//传阅
export const doChuanyue = (destuserid = '') => {
	controlForward({showForward:true, forwardflag:"4"});
}

//超时设置
export const onNewOverTime = () =>{
	
}



//新建流程
export const onNewRequest = (workflowid,requestid,agent) => {

}


/**新建短信（短信督办）   by  lijia 2018-12-28***************/
export const onNewSms = () => {
	const { commonParam } = base.wfGlobalStore;
	const { requestid } = commonParam;
	EmSDK.openSendMsg(requestid);
}
//新建邮件（邮件督办）
export const onNewEmail = () => {
	const { commonParam } = base.wfGlobalStore;
	const { requestid } = commonParam;
	EmSDK.openSendEmail(requestid);
	
}
/**********by  lijia 2018-12-28***************/

//关于版本
export const aboutVersion = (versionid) => {
	Common.showConfirm({
		title: getLabel(386181,'当前是') + "V" + versionid + "  " +  getLabel(567,"版本"),
	}, false);
}

//流转设定
export const doFreeWorkflow = () =>{
	const { wfGlobalStore,wfOperateStore } = base;
	const { commonParam,belongUserStr } = wfGlobalStore;
	const { rightMenu } = wfOperateStore;
	const { requestid,workflowid,nodeid,iscreate,f_weaver_belongto_userid,f_weaver_belongto_usertype, selectNextFlowPattern } = commonParam;
	const { iscnodefree,isFree,freewftype,freeNode = {} } = rightMenu;
	const {initroad = '-1',initfrms = '-1'} = freeNode;
	//自由流程
	let url = "";
	// if(isFree == "1"){
		
	// }else{
		if(iscreate == "1" && selectNextFlowPattern != 0){
			Modal.confirm({
				title: getLabel(131329,'信息确认'),
				content:getLabel(21798,"流程数据还未保存，现在保存吗? "),
				okText:getLabel(826,'确定'),
				cancelText:getLabel(201,'取消'),
				onOk(){
					doSubmitForm({actiontype:"requestOperation", src:"save"});
				}
			});
		}else{
			if(selectNextFlowPattern == 0){//简易模式 0才是建议模式
				Util.scrollDom(".wf-req-freeWorkflowSimple",true,getLabel(520577,"请确认流转设定设置"));
			}else{
				window.historyRoute.push({
					pathname:'/req/wfFreeFlowSet',
					search:`?requestid=${requestid}&_workflowid=${workflowid}`
				});
			}
		}
	// }
}

//触发子流程
export const triSubwf2 = (subwfid, workflowNames,requestType) =>{
	const { wfGlobalStore } = base;
	const { commonParam } = wfGlobalStore;
	workflowNames = workflowNames.replace(new RegExp(',',"gm"),'\n');
	Common.showConfirm({
		title:getLabel(131329,'信息确认'),
		okText:getLabel(826,'确定'),
		cancelText:getLabel(201,'取消'),
		content: getLabel(25394,'确定触发') + ":"+workflowNames+getLabel(386183,"流程吗?"),
        okEvent :() =>{

			const callFun = ()=>{
				wfGlobalStore.setLoading(true);
				const { requestid,nodeid,f_weaver_belongto_userid,f_weaver_belongto_usertype } = commonParam;
				const params = {requestId:requestid, nodeId:nodeid, paramSubwfSetId:subwfid, f_weaver_belongto_userid, f_weaver_belongto_usertype};
				API_REQ.triggerSubWf(params).then(data => {
					wfGlobalStore.setLoading(false);
					Common.showConfirm({
						title: data.msg,
						okEvent: () =>{

							Util.reloadRequestPage({requestid: requestid});
						}
					}, false);
				});
			}

			//先执行保存
			(requestType != 0) && doSubmitForm({
				actiontype:"requestOperation",
				src:"save",
				saveCallFun : callFun
			});
			(requestType == 0) && callFun();
		},
		cancelEvent:()=>{
			const { controlVariableMap } = base.allStores.wfSignInputStore;
			controlVariableMap(VariableKeys.CURR_OPERATE_TYPE,{});
		}
	});
}

export const doAffirmanceBack = () =>{
	base.wfOperateStore.setSubmitToNodeId();
	doSubmitForm({actiontype:"requestOperation", src:"save", needwfback:"1", isaffirmance:"1"});
}

export const doAffirmanceNoBack = () =>{
	base.wfOperateStore.setSubmitToNodeId();
	doSubmitForm({actiontype:"requestOperation", src:"save", needwfback:"0", isaffirmance:"1"});
}

/**分享到EM   by  lijia 2018-12-28***************/
export const doShare = () => {
	base.wfOperateStore.setShareMsgInfo();
	window.historyRoute.push(base.wfOperateStore.share.path);
}

/************by  lijia 2018-12-28************** */

//流程编辑
export const doEdit = () =>{
	const { requestid } = base.wfGlobalStore.commonParam;
	Util.reloadRequestPage({reEdit:"1", requestid:requestid});
}

//明细导入
export const doImportDetail = () =>{
	
}

export const doImportWorkflow =()=>{
    const {variableMap,controlVariableMap} = base.wfGlobalStore;
    let reqImportStore = variableMap.get('reqImportStore');
    if(!variableMap.has('reqImportStore')) {
        reqImportStore = new Browser.Store({route: '/req', id: 'import'});
        controlVariableMap('reqImportStore', reqImportStore);
	}
    window.historyRoute.push(reqImportStore.path);
}

//转发收回
export const doTakeBack = () => {
	const { commonParam } = base.wfGlobalStore;
	const { submitParam = {} } = base.wfOperateStore;
	const { requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype,workflowid } = commonParam;
	const { agentType, takisremark, agentorByAgentId } = submitParam;
    API_REQ.doTakeBack({workflowid, requestId : requestid, f_weaver_belongto_userid : f_weaver_belongto_userid, f_weaver_belongto_usertype : f_weaver_belongto_usertype, agentType:agentType, takisremark:takisremark, agentorByAgentId:agentorByAgentId}).then((reVal)=>{
        Util.reloadRequestPage({requestid});
    });
}

//结束征询
export  const doTakEnd = () => {
	const {commonParam} = base.wfGlobalStore;
	const { submitParam = {}, rightBtnName = {} } = base.wfOperateStore;
	const { requestid,workflowid } = commonParam;
	const { agentType, agentorByAgentId } = submitParam;
	let label = getLabel(510675,'确定要结束意见征询吗？');
	if(rightBtnName['BTN_TAKEND']) {
		label = getLabel(519120, '确定要{1}吗？').replace("{1}", rightBtnName['BTN_TAKEND']);
	}
	Common.showConfirm({
		title:getLabel(131329,'信息确认'),
		okText:getLabel(826,'确定'),
		cancelText:getLabel(201,'取消'),
		content: label,
        okEvent :() =>{
			API_REQ.doTakEnd({
				requestid: requestid,
				workflowid,
				agentType,
				agentorByAgentId
			}).then(data => {
				if(!data.result && data.msg) {
					Toast.info(data.msg, 2);
					try {
						window.setTimeout(() => {
							
							Util.reloadRequestPage({requestid});
						}, 2000);
					} catch (e) {}
				} else {
					Util.reloadRequestPage({requestid});
				}
			});
		}
	});
}


//撤回
export const doWithdraw = () => {
	const showSignArea = SignUtil.getVariableMapVal(VariableKeys.SHOW_SIGN_AREA, false);
	const { wfOperateStore } = base.allStores;
	const {getReqWithDrawInfo,reqWithDrawSubmit,reWithDrawInfo,isRemind = '1'} = wfOperateStore;
	if(showSignArea) {
		const {allowRemind, recallNodeName} = reWithDrawInfo;
		if(SignUtil.verifyRemark({needVeiryRequired:true})) {
			let tipInfo = getLabel(516798, '确定要将流程撤回到“$nodename$”节点吗?');
			tipInfo = tipInfo.replace('$nodename$', recallNodeName);
			tipInfo = tipInfo.replace('$nodeName $', recallNodeName);//英文环境下翻译偏差
            let children = [];
            children.push(React.createElement('div',{},tipInfo));

            if(allowRemind) {
                children.push(React.createElement(Checkbox,{'defaultChecked':isRemind == '1','onChange':(e)=>{
                        const value = e.target.checked ? "1" : "0";
                        wfOperateStore.isRemind = value;
                }},getLabel(515992, '通知已提交流程的操作者')));
            }

            let contentCom = React.createElement('div',{},children);
			Common.showConfirm({content:contentCom,okEvent:reqWithDrawSubmit});
		}
	} else {
		getReqWithDrawInfo();
	}
}


/**
 * 自定义操作菜单
 * @param reqid
 * @param wfid
 * @param menuid
 * @param nodeid
 */
export const onCustomOpt =(reqid,wfid, menuid,nodeid) =>{
	const { commonParam , urlParams = {}} = base.wfGlobalStore;
	const { requestid,wfmonitor,isurger,f_weaver_belongto_userid,f_weaver_belongto_usertype,isremark } = commonParam;
	const ismonitor = wfmonitor ? "1" : "0";
	const urger = isurger ? "1" : "0";


	//controlDialogVisible(type.IMPORT_WF_DETAIL_MODAL,true);
	//alert("onCustomOpt"+" menuid = "+menuid);
	const params = {requestId:reqid, nodeId:nodeid, workflowId:wfid,setid:menuid,ismonitor:ismonitor,urger:urger,f_weaver_belongto_userid:f_weaver_belongto_userid, f_weaver_belongto_usertype:f_weaver_belongto_usertype};
	try {
		API_REQ.getCustomOperation(params).then(data => {
			let hassave =  data.ismustsave ;
			if(requestid == "-1"&&hassave==='1'){//需要保存
				getAntd().Modal.confirm({
					title:getLabel(131329,'信息确认'),
					content:getLabel(21798,"流程数据还未保存，现在保存吗? "),
					okText:getLabel(826,'确定'),
					cancelText:getLabel(201,'取消'),
					onOk(){
						doSubmitForm({actiontype:"requestOperation", src:"save"});
					}
				});
			}else {

				let actioniserror = false;
				let datalist = data.CustomOperationFunList;
				for (var i in datalist) {
					let opttype = datalist[i].cusopttype;//操作方式
					let actionname = datalist[i].mobileurl;//url or actionname
					let pageurl = datalist[i].actionname;//url or actionname
					if(actionname==''){
						actionname = pageurl ;
					}
					let actiontype = datalist[i].actiontype;//opentype or actiontype
					let actionfrom = datalist[i].actionfrom;//action
					let tempuserid = datalist[i].userid;//userid
					if(actioniserror){
						break ;
					}
					if (opttype === '0') {//打开URL
						if(actionname==''){
							Bubble.error(getLabel(502427,'链接地址为空'), 2);
							continue ;
						}
						actionname = getCustomOptUrlValues(actionname,tempuserid);
						if (Util.judgeSupportOpenSDK()) {
							window.em.openLink({
								openType: 2,
								title: "",
								url: actionname
							});

						} else {
							Util.forwardPage(actionname);

						}
					} else if (opttype === '1') {
						if((isremark=== '2'||isremark === '4') && (actiontype != '0' && actiontype != '3' && actiontype!= '10')){
							//getAntd().message.error(getLabel(132382,'没有权限，无法操作'),3);
							Bubble.error(getLabel(132382,'没有权限，无法操作'), 2);
							continue ;
						}
						//流程相关操作
						if (actiontype === '0') {//刷新表单数据
							if(reqid>0) {
								base.wfGlobalStore.setLoading(false);
								Util.reloadRequestPage({requestid: reqid});
							}else{
								window.location.reload();
							}
						} else if (actiontype === '1') {//"提交/批准"
							this.doSubmitNoBack();
						} else if (actiontype === '2') {//"提交至退回节点"
							this.doSubmitDirect('submit');
						} else if (actiontype === '3') {//"转发"
							this.doReviewE9();
						} else if (actiontype === '4') {//"保存"
							this.doSave_nNew();
						} else if (actiontype === '5') {//"退回"
							this.doReject_New();
						} else if (actiontype === '6') {//"转办"
							this.doReview3();
						} else if (actiontype === '7') {//"意见征询"
							this.doReview2();
						} else if (actiontype === '8') {//"超时设置"
							this.onNewOverTime();
						} else if (actiontype === '9') {//"强制归档"
							this.doDrawBack();
						} else if (actiontype === '10') {//"强制收回"
							this.doRetract();
						} else if (actiontype === '11') {//传阅
							this.doChuanyue();
						}

					} else if (opttype === '2') {//字段赋值
						//TODO
					} else if (opttype === '3') {//附加操作
						const params1 = {
							requestId: reqid,
							nodeId: nodeid,
							workflowId: wfid,
							setid: menuid,
							actiontype: actiontype,
							actionname: actionname,
							actionfrom: actionfrom,
							f_weaver_belongto_userid: f_weaver_belongto_userid,
							f_weaver_belongto_usertype: f_weaver_belongto_usertype
						};

						API_REQ.runCustomOperationAction(params1).then(actiondata => {
							let flag = actiondata.CustomOperationActionResult.returnflag ;
							let msg = actiondata.CustomOperationActionResult.returnmsg ;
							if(flag === 'false') {
								//getAntd().message.error(msg,3);
								Bubble.error(msg, 2);
								actioniserror = true ;//出现异常后 后面的不执行
							}else{
								//getAntd().message.success(msg,2);
								Bubble.success(msg, 2);
							}
						});
					}
				}
			}
		});
	}catch (e) {
		if(window.console)	console.log(e);
	}

}


const getCustomOptUrlValues =(url,userid) =>{
	const { commonParam } = base.globalStore;
	const { requestid,workflowid,nodeid,formid } = commonParam;
	let regex = /\{[^\}]+\}/ ;

	//console.log("url = "+url);
	try {
		while (regex.test(url)) {
			//console.log("url = "+url);
			let str = regex.exec(url)[0];
			let e = "";
			//console.log("解析："+str);
			if (str != ''&&str!='{}') {
				let strnew = str.replace(new RegExp("\\{", "g"), "").replace(new RegExp("\\}", "g"), "");
				//console.log("str = "+str);
				if (strnew=='requestid') {
					e = requestid ;
				}else if (strnew=='workflowid') {
					e = workflowid ;
				}else if (strnew=='nodeid') {
					e = nodeid ;
				}else if (strnew=='userid') {
					e = userid ;
				}else if (strnew=='formid') {
					e = formid ;
				} else {
					try {
						e = WfForm_Public.getFieldValue("field" + strnew);
					}catch (e) {
						e = "";
					}
					//console.log("strnew = "+strnew+" e = "+e);
				}
				try {
					url = url.replace(new RegExp("\\{"+strnew+"\\}", "g"), e);
				}catch (e) {
					//console.log(e);
				}
			}

		}
	}catch(e){

	}
	//console.log(url);
	return url ;
}

/**钉钉中的DING功能 */
export const doDing = () =>{
	const {variableMap,controlVariableMap} = base.wfGlobalStore;
    let dingStore = variableMap.get('dingStore');
    if(!variableMap.has('dingStore')) {
		dingStore = new BrowserHrm.Store({route: '/req', id: 'wfDing'});
		dingStore.setState({activeKey:"8"})
		controlVariableMap('dingStore', dingStore);
		
	}
    window.historyRoute.push(dingStore.path);

}